<?php


namespace app\admin\model;


use think\facade\Db;
use think\Model;

class Category extends Model {
    public function article() {
        return $this->hasMany(Article::class, 'category_id')->
        hidden(['category_id', 'is_banner', 'status', 'update_time', 'create_time', 'image_url', 'content', 'author']);
    }

    public function child() {
        return $this->hasMany(Category::class, 'pid')->
        hidden(['pid', 'is_banner', 'status', 'update_time', 'create_time', 'is_main']);
    }


    public function getCategoryList() {
        $cate = $this->
        with('child')->
        withOutField(['pid', 'is_banner', 'status', 'update_time', 'create_time', 'is_main'])->
        where(['is_main' => 1])->
        where('is_banner', '<>', 1)->
        select();
        return $cate;
    }

    public function modCategoryIdByIds($category_id, $ids) {
        $res = Db::name('article')
            ->where('id', 'in', $ids)
            ->where('status', '<>', config('status.mysql.table_delete'))
            ->update([
                'category_id' => $category_id
            ]);
        return $res;
    }

    public function getArticleCountByCategoryId() {
        $categoryHidden = ['update_time', 'create_time', 'pid', 'is_banner', 'status', 'category_id'];
//        $list = $this->
//        withCount([
//            'article' => function ($query) {
//                $query->where('status', '<>', config('status.mysql.table_delete'));
//            }])->
//        hidden($categoryHidden)->
//        select();
        $list = $this->
        where('is_main', 1)->
        withCount(['article' => function ($query) {
            $query->where('status', '<>', config('status.mysql.table_delete'));
        }])->
        with([
            'child' => function ($query) {
                $query->withCount(['article' => function ($query) {
                    $query->where('status', '<>', config('status.mysql.table_delete'));
                }]);
            }])->
        hidden($categoryHidden)->
        select();
        return $list;
    }
}